//
//  LLZTabBar.m
//  xxShare
//
//  Created by 柳麟喆 on 2018/3/5.
//  Copyright © 2018年 lzLiu. All rights reserved.
//

#import "LLZTabBar.h"
#import "UIButton+LLZ.h"

@implementation LLZTabBar

- (UIButton *)centerBtn{
    if (!_centerBtn) {
        _centerBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 60)];
        [_centerBtn setImage:[UIImage imageNamed:@"添加-红色-32.png"] forState:UIControlStateNormal];
        __weak typeof(self)weakSelf = self;
        __weak typeof(_centerBtn)weakBtn = _centerBtn;
        
        [weakBtn addHander:^{
            if (weakSelf.centerBtnClick) {
                weakSelf.centerBtnClick(weakSelf, weakBtn);
            }
        }];
    
    }
    return _centerBtn;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    //取出tabBarButton
    NSMutableArray *tabBarButtonArray = [[NSMutableArray alloc]init];
    for(UIView *view in self.subviews){
        if ([view isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            [tabBarButtonArray addObject:view];
        }
    }
    
    CGFloat barWidth = self.bounds.size.width;
    CGFloat barHeight = self.bounds.size.height;
    CGFloat centerBarWidth = CGRectGetWidth(self.centerBtn.frame);
    //设置中间按钮的位置
    self.centerBtn.center = CGPointMake(barWidth/2, barHeight/2);
    //重新布局其他tabBarItem的宽度
    CGFloat barItemWidth = (barWidth - centerBarWidth) / tabBarButtonArray.count;
    [tabBarButtonArray enumerateObjectsUsingBlock:^(UIView *  _Nonnull view, NSUInteger idx, BOOL * _Nonnull stop) {
        CGRect frame = view.frame;
        if (idx >= tabBarButtonArray.count / 2) {
            // 重新设置 x 坐标，如果排在中间按钮的右边需要加上中间按钮的宽度
            frame.origin.x = centerBarWidth + idx * barItemWidth;
        }else{
            frame.origin.x = idx * barItemWidth;
        }
        // 重新设置宽度
        frame.size.width = barItemWidth;
        view.frame = frame;
    }];
    // 把中间按钮带到视图最前面
    [self addSubview:self.centerBtn];
    [self bringSubviewToFront:self.centerBtn];
    
}

@end
